package com.oig.sys.workflow.app.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.sys.workflow.app.IAppFlowConfigService;
import com.oig.sys.workflow.dto.FlowConfigDto;
import com.oig.sys.workflow.flow.IDepFlowService;
import com.oig.sys.workflow.service.ITbFlowConfigService;
import com.oig.sys.workflow.vo.FlowConfigVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class AppFlowConfigServiceImpl implements IAppFlowConfigService {

    private final ITbFlowConfigService flowConfigService;
    private final IDepFlowService depFlowService;

    @Override
    public FlowConfigVo queryFlowDefine(String flowCode) {
        return depFlowService.queryFlowDefine(flowCode);
    }

    @Override
    public FlowConfigVo addFlowConfig(FlowConfigDto flowConfigDto) {
        FlowConfigVo flowConfigVo = flowConfigService.addFlowConfig(flowConfigDto);
        boolean isOpen = this.depFlowService.subscribe(flowConfigVo.getFlowCode());
        log.debug("开启订阅结果：{}", isOpen);
        if (isOpen){
            this.flowConfigService.updateSubscribe(flowConfigVo.getId(),CommonEnum.FlagEnum.TRUE_FLAG.getCode());
        }
        return flowConfigVo;
    }

    @Override
    public FlowConfigVo updateFlowConfig(FlowConfigDto flowConfigDto) {
        return flowConfigService.updateFlowConfig(flowConfigDto);
    }

    @Override
    public void cancelFlowConfig(Integer id) {
        flowConfigService.cancelFlowConfig(id);
    }

    @Override
    public void subscribe(Integer id) {
        FlowConfigVo flowConfigVo = this.getFlowConfig(id);
        boolean isOpen = this.depFlowService.subscribe(flowConfigVo.getFlowCode());
        log.debug("开启订阅结果：{}", isOpen);
        if (isOpen){
            this.flowConfigService.updateSubscribe(flowConfigVo.getId(), CommonEnum.FlagEnum.TRUE_FLAG.getCode());
        }
    }

    @Override
    public void unsubscribe(Integer id) {
        FlowConfigVo flowConfigVo = this.getFlowConfig(id);
        boolean isClose = this.depFlowService.unsubscribe(flowConfigVo.getFlowCode());
        log.debug("取消订阅结果：{}", isClose);
        if (isClose){
            this.flowConfigService.updateSubscribe(flowConfigVo.getId(), CommonEnum.FlagEnum.FALSE_FLAG.getCode());
        }
    }

    @Override
    public FlowConfigVo getFlowConfig(Integer id) {
        return flowConfigService.getFlowConfig(id);
    }
}
